package com.example.bm.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.example.bm.system.service.BankService;
import com.example.bm.system.service.RegionService;
import com.example.dao.model.TBank;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BankDataListener extends AnalysisEventListener<ExcelBankEntity> {

    private static final int BATCH_COUNT = 3000;
    private List<ExcelBankEntity> list = new ArrayList<>();

    private RegionService regionService;
    private BankService bankService;

    public BankDataListener(RegionService regionService, BankService bankService) {
        this.regionService = regionService;
        this.bankService = bankService;
    }

    @Override
    public void invoke(ExcelBankEntity excelBankEntity, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(excelBankEntity));
        list.add(excelBankEntity);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            log.info("解析到{}条数据", list.size());
            saveData(list);
            // 存储完成清理 list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData(list);
        log.info("所有数据解析完成！");
    }


    /**
     * 加上存储数据库
     */
    private void saveData(List<ExcelBankEntity> entities) {
        log.info("insert batch start");
        Long start = System.currentTimeMillis();
        List<TBank> banks = Lists.newArrayList();
        entities.forEach(obj -> {
//            TRegion region = regionService.getOne(new LambdaQueryWrapper<TRegion>()
//                    .eq(TRegion::getRegionCode, obj.getBankCode()));
            TBank bank = TBank.builder()
                    .bankCode(obj.getBankCode())
                    .bankName(obj.getFullName())
                    .shortName(obj.getBankName())
                    .isEnable(1)
                    .build();
            banks.add(bank);

        });
        this.bankService.saveBatch(banks);
        Long end = System.currentTimeMillis();
        log.info("insert batch end ,size={}, cost={}", banks.size(), (end - start) / 1000);
    }
}
